package com.fx.easyexcel.demo.controller;

import com.alibaba.excel.EasyExcel;
import com.fx.easyexcel.demo.listener.ExaminerListener;
import com.fx.easyexcel.demo.pojo.Examiner;
import com.fx.easyexcel.demo.pojo.ResponseResult;
import com.fx.easyexcel.demo.service.FileService;
import com.fx.easyexcel.demo.service.ReadExcelToPdfService;
import com.fx.easyexcel.demo.util.TimeUtil;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Objects;

/**
 * @author Faxon
 * @version 1.0
 * @date 2020-06-30 21:59
 **/
@RestController
public class ReadExcelController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ReadExcelController.class);

    @Resource
    ReadExcelToPdfService readExcelService;

    @Resource
    FileService fileService;

    @Value("${output.pdfPath}")
    public String pdfPath;


    @GetMapping("/getExcel")
    public String getExcel() {
        return "Hello";
    }

    @PostMapping("/uploadAndRead")
    public ResponseResult<String> uploadAndRead(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
        File toFile = null;
        try {
            //将MultipartFile转File对象
            toFile = fileService.toFile(file);
        } catch (IOException e) {
            LOGGER.error("Message：[{}]，Time：[{}],Class:[{}]" ,"MultipartFile转File对象失败",
                    TimeUtil.getNowTime(),this.getClass().getName());
            e.printStackTrace();
            return new ResponseResult<>(500,"MultipartFile转File对象失败");
        }
        //读取Excel数据，并在readExcelService形成pdf文件
        LOGGER.info("读取Excel数据中....");
        EasyExcel.read(toFile, Examiner.class, new ExaminerListener(readExcelService)).sheet().doRead();
        //删除生成的File文件
        FileUtils.deleteQuietly(toFile);
        LOGGER.info("读取完成，Pdf生成完毕..");
        File pdfs = new File(pdfPath);
        File[] files = pdfs.listFiles();
        if(files==null || files.length == 0){
            LOGGER.info("模板文件不匹配，或数据为空,未生成pdf文件,"+TimeUtil.getNowTime());
            return new ResponseResult<>(500,"PDF_ERROR");
        }
        //压缩PDF文件
        LOGGER.info("压缩文件中..");
        File zip = fileService.toZip(pdfPath,  fileService.getFileName(file));
        //压缩结束后删除pdf(异步)
        LOGGER.info("压缩完成，正在删除临时文件..");
        fileService.deleteDir(pdfs);
        LOGGER.info("已删除临时文件..");
        if (zip == null) {
            return new ResponseResult<>(501,"ZIP_ERROR");
        }
        return new ResponseResult<>(200,"解析成功",zip.getName());
    }

    @GetMapping("/getZip/{fileName}")
    public void getZip(@PathVariable("fileName") String fileName, HttpServletResponse response){
        File file = new File(fileName);
        try {
            fileService.downloadFile(response, file.getName(), new FileInputStream(file));
            FileUtils.deleteQuietly(file);
        } catch (IOException e) {
            LOGGER.error("Message：[{}]，Time：[{}],Class:[{}]" ,"zip文件写入response失败",
                    TimeUtil.getNowTime(),this.getClass().getName());
            e.printStackTrace();
        }
    }
}
